from django.http import HttpResponse, StreamingHttpResponse
from django.template import loader
import csv


# TODO: 生成小的csv文件
def index(request):
    # 1.指定content_type为text/csv
    response = HttpResponse(content_type='text/csv')
    # 2.设置响应头Content-Disposition，attachment作为附件下载，指定文件名abc.csv
    response['Content-Disposition'] = 'attachment;filename="abc.csv"'
    # 3.使用csv模块的writer方法，将相应的数据写入到response中
    writer = csv.writer(response)
    writer.writerow(['姓名', '年龄', '体重'])
    writer.writerow(['张三', 18, 170])
    writer.writerow(['李四', 20, 180])
    return response


# TODO: 将CSV文件定义成模板
def csv_template(request):
    context = {
        "rows": [
            ['姓名', '年龄', '体重'],
            ['张三', 18, 170],
            ['李四', 20, 180]
        ]
    }
    # 1.指定content_type为text/csv
    response = HttpResponse(content_type='text/csv')
    # 2.设置响应头Content-Disposition，attachment作为附件下载，指定文件名abc.csv
    response['Content-Disposition'] = 'attachment;filename="csv_template.csv"'
    # 3.加载模板
    t = loader.get_template('csv.html')
    # 4.写入模板数据
    response.write(t.render(context=context))
    return response


# TODO: 生成大的CSV文件
def large_csv_demo(request):
    # 1.使用HttpResponse生成
    # response = HttpResponse(content_type='text/csv')
    # response['Content-Disposition'] = 'attachment;filename="csv_template.csv"'
    # writer = csv.writer(response)
    # for i in range(1000000):
    #     writer.writerow(['row %s' % i, '%s' % i])

    # 2.使用StreamingHttpResponse
    rows = ("row %s,%s\n" % (i, i) for i in range(1000000))
    response = StreamingHttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment;filename="large_csv_demo.csv"'
    response.streaming_content = rows
    return response
